<template>
	<!-- 固定的分类导航栏525555555111 -->
	<view ref="categoryRefDing" class="category-nav-container-ding"
		:style="{ display: fixedCategoryVisible ? 'block' : 'none' }">
		<view class="category-nav fixed"
			style="top: 0; left: 0; right: 0; padding: 0 10px; overflow-x: auto; white-space: nowrap; background-color: #f7f7f7; transition: all 0.3s ease;">
			<view ref="categoryScroll" class="category-scroll"
				style="height: 100%; display: flex; align-items: center; padding: 6px 0; white-space: nowrap; position: relative;">
				<!-- 硬编码的"最新"分类 -->
				<view ref="categoryLatest" class="category-item item"
					:class="{ 'active': currentCategory === 'latest' }" @click="changeCategory('latest')"
					data-index="-1"
					style="display: inline-block; margin: 0 5px; padding: 10rpx 0rpx; border-radius: 40rpx; transition: all 0.3s ease;">
					最新
				</view>

				<!-- 动态生成的分类 -->
				<view v-for="(item, index) in categories" :key="item.id" ref="categoryItemRefs"
					class="category-item item" :class="{ 'active': currentCategory === item.id }"
					@click="changeCategory(item.id)" data-index="{{index}}"
					style="display: inline-block; margin: 0 5px; padding: 10rpx 0rpx; border-radius: 40rpx; transition: all 0.3s ease;">
					{{ item.fenleiName }}
				</view>
			</view>
		</view>
	</view>

	<view class="container" style="display: flex; flex-direction: column; height: 100%; background-color: #fff; ">
		<scroll-view ref="scrollContainer" class="z-paging-container" scroll-y :scroll-top="scrollTop"
			@scroll="onScroll" :refresher-enabled="true" :refresher-triggered="isRefreshing"
			@refresherrefresh="handleRefresh" @scrolltolower="loadMore" enhanced :style="{ height: scrollViewHeight }">

			<!-- 自定义搜索栏 -->
			<view @click="toSouSuo" id="zidingyisousuolan" class="search-bar"
				style="padding: 20rpx; background-color: #fff;">
				<view class="search-input-container" style="position: relative; width: 100%;">
					<input v-model="searchValue" type="text" placeholder="请输入您想搜索的内容" @confirm="onSearch"
						placeholder-style="color: #7eb6ff; font-size: 26rpx;"
						style="width: 100%; height: 70rpx; padding-left: 70rpx; background-color: #fff; border: 1rpx solid #7eb6ff; border-radius: 35rpx; font-size: 14px; color: #7eb6ff; box-sizing: border-box; outline: none;" />
					<image src="https://paole.hebeixiaoyu.cn/run/profile/upload/sousuo.png" mode="aspectFit"
						style="position: absolute; left: 20rpx; top: 50%; transform: translateY(-50%); width: 32rpx; height: 32rpx; color: #7eb6ff;" />
				</view>
			</view>

			<!-- 快捷入口 -->
			<view class="quick-actions"
				style="height: auto; padding: 30rpx 0rpx;  flex-wrap: nowrap; background-color: #fff; ">
				<view class="action-item" @click="navigateTo('helpFetch')"
					style="width: 20%; display: flex; flex-direction: column; align-items: center; padding: 10rpx 0;">
					<image src="https://paole.hebeixiaoyu.cn/run/profile/upload/kuaididaiqu.jpg" mode="aspectFill"
						style="width: 50px; height: 50px;">
					</image>
					<text style="font-size: 24rpx; margin-top: 12rpx; color: #333;">快递代取</text>
				</view>
				<view class="action-item" @click="showQiangWei"
					style="width: 20%; display: flex; flex-direction: column; align-items: center; padding: 10rpx 0;">
					<image src="https://paole.hebeixiaoyu.cn/run/profile/upload/qiangweixin.jpg" mode="aspectFill"
						style="width: 50px; height: 50px;border-radius: 35%;">
					</image>
					<text style="font-size: 24rpx; margin-top: 12rpx; color: #333;">加墙墙VX</text>
				</view>
				<view class="action-item" @click="navigateTo('helpWith-wm')"
					style="width: 20%; display: flex; flex-direction: column; align-items: center; padding: 10rpx 0;">
					<image src="https://paole.hebeixiaoyu.cn/run/profile/upload/waimaidaiqu.jpg" mode="aspectFill"
						style="width: 50px; height: 50px;">
					</image>
					<text style="font-size: 24rpx; margin-top: 12rpx; color: #333;">外卖代拿</text>
				</view>
				<view class="action-item" @click="tiaoZhuanShouYe"
					style="width: 20%; display: flex; flex-direction: column; align-items: center; padding: 10rpx 0;">
					<image src="https://paole.hebeixiaoyu.cn/run/profile/upload/sushechaoshi.jpg" mode="aspectFill"
						style="width: 50px; height: 50px;">
					</image>
					<text style="font-size: 24rpx; margin-top: 12rpx; color: #333;">宿舍超市</text>
				</view>
				<view class="action-item" @click="navigateTo('errand')"
					style="width: 20%; display: flex; flex-direction: column; align-items: center; padding: 10rpx 0;">
					<image src="https://paole.hebeixiaoyu.cn/run/profile/upload/xiaoyuanpaotui.jpg" mode="aspectFill"
						style="width: 50px; height: 50px;">
					</image>
					<text style="font-size: 24rpx; margin-top: 12rpx; color: #333;">校园跑腿</text>
				</view>
			</view>

			<!-- 今日热榜和热榜词条 -->
			<view class="hot-rank"
				style="height: 100rpx; padding: 0 24rpx; border-radius: 16rpx;  display: flex; align-items: center; background-color: #fff;"
				@click="toJinRiReBang">
				<view style="flex-direction: column; display: flex; margin-right: 34rpx; font-style: italic;">
					<text style="font-size: 34rpx; font-weight: 900; color: #3d91ff;">今日</text>
					<text style="font-size: 34rpx; font-weight: 900; color: #ff4d4f;">热榜</text>
				</view>
				<view style="flex: 1; height: 100%; overflow: hidden; position: relative;">
					<swiper class="rank-swiper" :autoplay="true" :interval="3000" :duration="500" circular vertical
						style="height: 100%;">
						<swiper-item v-for="(item, index) in hotList" :key="index">
							<view class="rank-item" style="display: flex; align-items: center; height: 100rpx;">
								<!-- <text class="rank-number"
									style="width: 48rpx; height: 48rpx; line-height: 48rpx; border-radius: 24rpx; background-color: #ff4d4f; color: #fff; text-align: center; font-size: 26rpx; margin-right: 16rpx;">{{ index + 1 }}</text>
								 -->
								<text class="rank-number" :style="{
								    backgroundColor: getRankColor(index),
								    color: index < 3 ? '#fff' : '#666' ,
								  }">
									{{ index + 1 }}
								</text>
								<text class="rank-title"
									style="flex: 1; font-size: 26rpx; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">{{ item.content || item.title }}</text>
							</view>
						</swiper-item>
					</swiper>
				</view>
				<text class="more" style="font-size: 26rpx; color: #999; margin-left: 10rpx;"
					@click="showMoreHot">更多</text>
			</view>

			<!-- 分类导航 - 添加固定的"最新"分类 -->
			<view ref="categoryRef" class="category-nav-container" style="z-index: 5;">
				<view class="category-nav" :class="{ 'fixed': categoryFixed }"
					style="top: 0; left: 0; right: 0; padding: 0 10px; overflow-x: auto; white-space: nowrap; background-color: #f7f7f7; transition: all 0.3s ease;">
					<view ref="categoryScroll" class="category-scroll"
						style="height: 100%; display: flex; align-items: center; padding: 6px 0; white-space: nowrap; position: relative;">
						<!-- 硬编码的"最新"分类 -->
						<view ref="categoryLatest" class="category-item item"
							:class="{ 'active': currentCategory === 'latest' }" @click="changeCategory('latest')"
							data-index="-1"
							style="display: inline-block; margin: 0 5px; padding: 10rpx 0rpx; border-radius: 40rpx; transition: all 0.3s ease;">
							最新
						</view>

						<!-- 动态生成的分类 -->
						<view v-for="(item, index) in categories" :key="item.id" ref="categoryItemRefs"
							class="category-item item" :class="{ 'active': currentCategory === item.id }"
							@click="changeCategory(item.id)" data-index="{{index}}"
							style="display: inline-block; margin: 0 5px; padding: 10rpx 0rpx; border-radius: 40rpx; transition: all 0.3s ease;">
							{{ item.fenleiName }}
						</view>
					</view>
				</view>
			</view>

			<!-- 帖子列表 -->
			<view v-for="(item, index) in zhiDingList" :key="item.id" class="post-card"
				style="position:relative; #fff; margin-bottom: 3px; border-radius: 8px; box-shadow: 0px 20px 17px 8px rgba(0,0,0,0.05); transition: transform 0.2s ease; padding:4px"
				@mouseenter="item.hover = true" @mouseleave="item.hover = false" @click="toDetail(item)">

				<view class="post-header"
					style="padding: 12px 12px; display: flex; align-items: center; justify-content: space-between;">
					<view style="display: flex; align-items: center;">
						<view v-if="item.niMingId==null||item.niMingId==''" style="    height: 80rpx;
																						display: flex;
																						align-items: center;">
							<van-image v-if="item.avatarText" :src="item.avatarText" round
								style="width: 80rpx; height: 80rpx; margin-right: 10px;  border-radius: 50px;" />
							<van-image v-else src="https://paole.hebeixiaoyu.cn/run/profile/upload/nimingtouxiang.png"
								round style="width: 80rpx; height: 80rpx; margin-right: 10px;  border-radius: 50px;" />
							<text class="username"
								style="font-size: 28rpx; font-weight: 500; color: #1A1A1A;">{{ item.username || '神秘同学' }}</text>
						</view>
						<view v-else style="    height: 80rpx;
													display: flex;
													align-items: center;">
							<van-image v-if="item.niMingTouimg" :src="item.niMingTouimg" round
								style="width: 80rpx; height: 80rpx; margin-right: 10px;  border-radius: 50px;" />
							<van-image v-else src="https://paole.hebeixiaoyu.cn/run/profile/upload/nimingtouxiang.png"
								round style="width: 80rpx; height: 80rpx; margin-right: 10px;  border-radius: 50px;" />
							<text class="username"
								style="font-size: 28rpx; font-weight: 500; color: #1A1A1A;">{{ item.niMingName || '神秘同学' }}</text>
						</view>
					</view>
					<text class="time"
						style="font-size: 24rpx; color: #999;">{{ formatTime(item.createTime || new Date()) }}</text>
					<text style="       position: absolute;
											top: 10rpx;
											right: 10rpx;
											font-size: 9px;
											background: linear-gradient(135deg, #9c27b0, #6a11cb);
											    color: white;
											padding: 2px 4px;">
						置顶
					</text>
				</view>

				<view class="post-content" style="padding: 0 12px 14px 12px;">
					<text class="desc" style="font-size: 26rpx; color: #333; line-height: 1.5;  display: -webkit-box;
					  -webkit-line-clamp: 3;
					  -webkit-box-orient: vertical;
					  overflow: hidden;">
						{{ item.content }}
					</text>
				</view>

				<view v-if="item.images" class="post-images">
					<van-grid column-num="3" :border="false">
						<van-grid-item use-slot v-for="(imgUrl, imgIndex) in item.images.split(',')" :key="imgIndex">
							<van-image width="180rpx" height="180rpx" radius="10px" :src="imgUrl" />
						</van-grid-item>
					</van-grid>
				</view>

				<view class="post-footer"
					style="padding: 0 12px 15px 12px; display: flex; align-items: center; justify-content: space-between;">
					<view class="post-tags" style="display: flex; gap: 10rpx;">
						<view class="tag-item" v-if="item.atiezifenleiName" :key="item.id"
							style="display: flex; align-items: center;">
							<image src="https://paole.hebeixiaoyu.cn/run/profile/upload/biaoqian.png" mode="aspectFit"
								style="width: 24rpx; height: 24rpx; margin-right: 5rpx;" />
							<text style="font-size: 22rpx; color: #666;">{{ item.atiezifenleiName }}</text>
						</view>
					</view>

					<view class="interaction" style="display: flex; align-items: center; gap: 30rpx;">
						<view class="like-btn" @click.stop="onGiveLike(item.id)"
							style="display: flex; align-items: center; gap: 5rpx;">
							<image
								:src="item.likestatus === 1 ? 'https://paole.hebeixiaoyu.cn/run/profile/upload/dianzanhongse.png' : 'https://paole.hebeixiaoyu.cn/run/profile/upload/dianzanheise.png'"
								mode="aspectFit"
								:style="{width: '36rpx', height: '36rpx', color: item.likestatus === 1 ? '#e5404f' : '#999'}" />
							<text style="font-size: 24rpx; color: #666;">{{ item.likeCount || 0 }}</text>
						</view>
						<view class="comment-btn" style="display: flex; align-items: center; gap: 5rpx;">
							<image src="https://paole.hebeixiaoyu.cn/run/profile/upload/pinglunheise.png"
								mode="aspectFit" :style="{width: '36rpx', height: '36rpx', color: '#3c91ff'}" />
							<text style="font-size: 24rpx; color: #666;">{{ item.commentCount || 0 }}</text>
						</view>
					</view>
				</view>
			</view>
			<view v-for="(item, index) in list" :key="item.id" class="post-card"
				style="position:relative; #fff; margin-bottom: 3px; border-radius: 8px; box-shadow: 0px 20px 17px 8px rgba(0,0,0,0.05); transition: transform 0.2s ease; padding:4px"
				@mouseenter="item.hover = true" @mouseleave="item.hover = false" @click="toDetail(item)">

				<view class="post-header"
					style="padding: 12px 12px; display: flex; align-items: center; justify-content: space-between;">
					<view style="display: flex; align-items: center;">
						<view v-if="item.niMingId==null||item.niMingId==''" style="    height: 80rpx;
																						display: flex;
																						align-items: center;">
							<van-image v-if="item.avatarText" :src="item.avatarText" round
								style="width: 80rpx; height: 80rpx; margin-right: 10px;  border-radius: 50px;" />
							<van-image v-else src="https://paole.hebeixiaoyu.cn/run/profile/upload/nimingtouxiang.png"
								round style="width: 80rpx; height: 80rpx; margin-right: 10px;  border-radius: 50px;" />
							<text class="username"
								style="font-size: 28rpx; font-weight: 500; color: #1A1A1A;">{{ item.username || '神秘同学' }}</text>
						</view>
						<view v-else style="    height: 80rpx;
													display: flex;
													align-items: center;">
							<van-image v-if="item.niMingTouimg" :src="item.niMingTouimg" round
								style="width: 80rpx; height: 80rpx; margin-right: 10px;  border-radius: 50px;" />
							<van-image v-else src="https://paole.hebeixiaoyu.cn/run/profile/upload/nimingtouxiang.png"
								round style="width: 80rpx; height: 80rpx; margin-right: 10px;  border-radius: 50px;" />
							<text class="username"
								style="font-size: 28rpx; font-weight: 500; color: #1A1A1A;">{{ item.niMingName || '神秘同学' }}</text>
						</view>
					</view>
					<text class="time"
						style="font-size: 24rpx; color: #999;">{{ formatTime(item.createTime || new Date()) }}</text>

				</view>

				<view class="post-content" style="padding: 0 12px 14px 12px;">
					<text class="desc" style="font-size: 26rpx; color: #333; line-height: 1.5;  display: -webkit-box;
					  -webkit-line-clamp: 3;
					  -webkit-box-orient: vertical;
					  overflow: hidden;">
						{{ item.content }}
					</text>
				</view>

				<view v-if="item.images" class="post-images">
					<van-grid column-num="3" :border="false">
						<van-grid-item use-slot v-for="(imgUrl, imgIndex) in item.images.split(',')" :key="imgIndex">
							<van-image width="180rpx" height="180rpx" radius="10px" :src="imgUrl" />
						</van-grid-item>
					</van-grid>
				</view>

				<view class="post-footer"
					style="padding: 0 12px 15px 12px; display: flex; align-items: center; justify-content: space-between;">
					<view class="post-tags" style="display: flex; gap: 10rpx;">
						<view class="tag-item" v-if="item.atiezifenleiName" :key="item.id"
							style="display: flex; align-items: center;">
							<image src="https://paole.hebeixiaoyu.cn/run/profile/upload/biaoqian.png" mode="aspectFit"
								style="width: 24rpx; height: 24rpx; margin-right: 5rpx;" />
							<text style="font-size: 22rpx; color: #666;">{{ item.atiezifenleiName }}</text>
						</view>
					</view>

					<view class="interaction" style="display: flex; align-items: center; gap: 30rpx;">
						<view class="like-btn" @click.stop="onGiveLike(item.id)"
							style="display: flex; align-items: center; gap: 5rpx;">
							<image
								:src="item.likestatus === 1 ? 'https://paole.hebeixiaoyu.cn/run/profile/upload/dianzanhongse.png' : 'https://paole.hebeixiaoyu.cn/run/profile/upload/dianzanheise.png'"
								mode="aspectFit"
								:style="{width: '36rpx', height: '36rpx', color: item.likestatus === 1 ? '#e5404f' : '#999'}" />
							<text style="font-size: 24rpx; color: #666;">{{ item.likeCount || 0 }}</text>
						</view>
						<view class="comment-btn" style="display: flex; align-items: center; gap: 5rpx;">
							<image src="https://paole.hebeixiaoyu.cn/run/profile/upload/pinglunheise.png"
								mode="aspectFit" :style="{width: '36rpx', height: '36rpx', color: '#3c91ff'}" />
							<text style="font-size: 24rpx; color: #666;">{{ item.commentCount || 0 }}</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 加载中提示 -->
			<view class="loading-container" v-if="loading">
				<van-loading type="spinner" color="#3c91ff" size="32rpx" />
				<text style="margin-left: 10rpx; font-size: 24rpx; color: #999;">加载中...</text>
			</view>

			<!-- 没有数据提示 -->
			<view class="no-data" v-if="!loading && !hasMoreData && list.length === 0">
				<text style="font-size: 24rpx; color: #999;">暂无数据</text>
			</view>

			<!-- 没有更多数据提示 -->
			<view class="no-more-data" v-if="!loading && !hasMoreData && list.length > 0" @click="gotoTop">
				<text style="font-size: 24rpx; color: #999;">没有更多数据了</text>
			</view>
		</scroll-view>
	</view>

	<!-- 发布按钮发帖按钮图片 -->
	<view class="post-button" @click="toPost">
		<van-image width="160rpx" height="160rpx" src="../../../static/image/post-button.png" />
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted,
		nextTick,
		watch
	} from 'vue';
	import {
		pageScrollTo
	} from '@dcloudio/uni-app';
	import dayjs from 'dayjs';

	import relativeTime from 'dayjs/plugin/relativeTime';
	import {
		onLoad,
		onShow,
		onUnload,
		onHide
	} from '@dcloudio/uni-app';



	import {
		getHotList,
		getCategories,
		getPosts,
		getZhiDingTieZi,
		getSchoolIdBy,
		likePost,
		getSchoolMengerPhone
	} from '@/api/xiaoquan.js';
	const getRankColor = (index) => {
		if (index === 0) return '#ff4d4f'; // 第1名：红色
		if (index === 1) return '#fc9e40'; // 第2名：橙色
		if (index === 2) return '#ffcd34'; // 第3名：深灰色
		return '#f5f5f5'; // 其他名次：浅灰色
	};
	const schoolId = ref('');
	const searchValue = ref('');
	const hotList = ref([]);
	const categories = ref([]);
	const list = ref([]);
	const zhiDingList = ref([])
	const currentPage = ref(1);
	const pageSize = ref(10);
	const currentCategory = ref('latest');
	const categoryFixed = ref(false);
	const categoryRef = ref(null);
	const categoryRefDing = ref(null);
	const categoryScroll = ref(null);
	const categoryItemRefs = ref([]);
	const categoryTop = ref(0);
	const loading = ref(false);
	const hasMoreData = ref(true);
	const isLoading = ref(false);
	const scrollContainer = ref(null);
	const scrollTop = ref(0);
	const fixedCategoryVisible = ref(false);
	let lastScrollTop = 0;
	let scrollTimeout = null;
	const isRefreshing = ref(false);
	const scrollViewHeight = ref('100%');
	let scrollDirection = 'down';
	const retryCount = ref(0);
	const MAX_RETRY = 3;
	const token = ref()
	dayjs.extend(relativeTime);
	onUnload(() => {
		console.log("销毁页面了")
	})
	onHide(() => {
		console.log("页面隐藏了")
	})
	onShow(async () => {
		// 判断是否登录，是否选择学习
		token.value = uni.getStorageSync("login_data")
		console.log(token.value, 234)
		if (!token.value) {
			// 显示提示文字
			wx.showToast({
				title: '请先登录',
				icon: 'none',
				duration: 1000 // 提示停留2秒
			});

			// 延迟2秒后跳转到登录页
			// setTimeout(() => {
			// 	wx.switchTab({
			// 		url: '/pages/mine/mine'
			// 	});
			// }, 1000);
		}
		// 每次查询一下用户学校id，并保存，如果没有则先选择学校
		let res = await getSchoolIdBy();
		schoolId.value = res.data;
		uni.setStorageSync('school_id', schoolId.value)
		console.log(res, 333333333)
		if (!schoolId.value) {

			wx.showToast({
				title: '请先选择学校',
				icon: 'none',
				duration: 1000 // 提示停留2秒
			});

			// 延迟2秒后跳转到登录页
			setTimeout(() => {
				uni.navigateTo({
					url: `/package/pages/selectSchool/selectSchool`
				});
			}, 1000);

			return;
		}

		fetchCategories().then(() => {
			fetchHotList();
			fetchPosts(1, currentCategory.value, '');
		});

		// 获取分类栏位置
		nextTick(() => {
			setTimeout(() => {
				uni.createSelectorQuery().select('.category-nav-container').boundingClientRect(
					rect => {
						if (rect) {
							categoryTop.value = rect.top;
						}
					}).exec();
			}, 300);
		});

	});

	const showQiangWei = () => {
		getSchoolMengerPhone().then((apiRes) => { // 将参数名改为 apiRes 避免冲突
			if (apiRes && apiRes.data) {
				uni.showModal({
					title: '墙墙の微信',
					content: apiRes.data, // 使用 apiRes 访问接口返回数据
					confirmText: '复制',
					cancelText: '取消',
					success: (modalRes) => { // 模态框回调参数改为 modalRes
						if (modalRes.confirm) {
							console.log('用户点击了确定');

							// 检查 apiRes.data 是否存在且为字符串
							if (typeof apiRes.data === 'string' && apiRes.data.trim() !== '') {
								uni.setClipboardData({
									data: apiRes.data,
									success: () => {
										uni.showToast({
											title: '微信已复制',
											icon: 'success'
										});
									},
									fail: (err) => {
										console.error('复制失败', err);
										uni.showToast({
											title: '复制失败，请稍后重试',
											icon: 'none'
										});
									}
								});
							} else {
								uni.showToast({
									title: '微信数据格式错误，无法复制',
									icon: 'none'
								});
							}
						}
					}
				});
			} else {
				uni.showToast({
					title: '获取客服微信失败',
					icon: 'none'
				});
			}
		}).catch((err) => {
			console.error('获取客服微信请求失败', err);
			uni.showToast({
				title: '网络请求失败，请稍后重试',
				icon: 'none'
			});
		});
	};

	// 修改后的时间格式化函数（不使用dayjs库）
	const formatTime = (time) => {
		// 处理不同格式的时间输入
		let inputTime;
		if (typeof time === 'number') {
			inputTime = new Date(time);
		} else if (typeof time === 'string') {
			inputTime = new Date(time);
			// 处理常见的时间字符串格式
			if (isNaN(inputTime.getTime())) {
				inputTime = new Date(Date.parse(time.replace(/-/g, '/')));
			}
		} else if (time instanceof Date) {
			inputTime = time;
		} else {
			inputTime = new Date();
		}

		const now = new Date();
		const timeDiff = now - inputTime;
		const minutesDiff = Math.floor(timeDiff / (1000 * 60));
		const hoursDiff = Math.floor(timeDiff / (1000 * 60 * 60));
		const daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
		// console.log(minutesDiff, hoursDiff, 22222222222)
		// 十分钟内显示"几分钟前"
		if (minutesDiff < 60 && minutesDiff >= 0) {
			if (minutesDiff == 0) {
				return "刚刚";
			}
			return `${minutesDiff}分钟前`;
		}
		// 一天内显示"几小时前"
		else if (hoursDiff < 24 && hoursDiff > 0) {
			return `${hoursDiff}小时前`;
		}
		// 其他时间显示原始时间（格式：YYYY-MM-DD HH:mm:ss）
		else {
			const year = inputTime.getFullYear();
			const month = String(inputTime.getMonth() + 1).padStart(2, '0');
			const day = String(inputTime.getDate()).padStart(2, '0');
			const hour = String(inputTime.getHours()).padStart(2, '0');
			const minute = String(inputTime.getMinutes()).padStart(2, '0');
			const second = String(inputTime.getSeconds()).padStart(2, '0');
			return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
		}
	};

	const toSouSuo = () => {
		uni.navigateTo({
			url: `/package/pages/suosuo/suosuo`
		});
	}
	const toJinRiReBang = () => {
		uni.navigateTo({
			url: "/package/pages/jinrirebang/jinrirebang"
		})
	}

	const fetchHotList = async () => {
		try {
			const response = await getHotList(schoolId.value);
			hotList.value = response.data || [];
		} catch (error) {
			console.error('获取热榜数据失败:', error);
		}
	};

	const fetchCategories = async () => {
		try {
			const response = await getCategories();

			categories.value = response.data || [];
		} catch (error) {
			console.error('获取分类数据失败:', error);
			uni.showToast({
				title: '获取分类数据失败',
				icon: 'none'
			});
		}
	};

	const fetchPosts = async (pageNo = 1, categoryId = null, searchKey = '') => {
		if (isLoading.value) return;
		isLoading.value = true;
		loading.value = true;

		try {
			let apiCategoryId = categoryId;
			if (categoryId === 'latest') {
				apiCategoryId = null;
			}

			// 每次查询的时候，查询一起查询出所有的置顶帖子。
			if (pageNo == 1) {
				const response = await getZhiDingTieZi(apiCategoryId, schoolId.value);
				zhiDingList.value = response.data;
			}

			const response = await getPosts(pageNo, pageSize.value, apiCategoryId, schoolId.value);

			if (!response || !response.data) {
				if (retryCount.value < MAX_RETRY) {
					retryCount.value++; // 直接递增重试计数
					// console.log(`加载失败，重试第 ${retryCount.value} 次`);
					setTimeout(() => fetchPosts(pageNo, categoryId, searchKey), 500);
					return;
				} else {
					hasMoreData.value = false;
					loading.value = false;
					retryCount.value = 0; // 重置重试计数
					return;
				}
			}

			const postsData = response.data;
			hasMoreData.value = postsData.length >= pageSize.value;

			if (pageNo === 1) {
				list.value = [];
			}

			if (Array.isArray(postsData) && postsData.length > 0) {
				const existingIds = new Set(list.value.map(item => item.id));
				const newPosts = postsData.filter(post => !existingIds.has(post.id));

				if (newPosts.length > 0) {
					list.value = [...list.value, ...newPosts];
					retryCount.value = 0; // 成功时重置重试计数
				} else if (pageNo > 1) {
					hasMoreData.value = false;
				}
			} else {
				hasMoreData.value = false;
			}

			currentPage.value = pageNo;
		} catch (error) {
			console.error('获取帖子列表失败:', error);
			if (retryCount.value < MAX_RETRY) {
				retryCount.value++;
				// console.log(`加载失败，重试第 ${retryCount.value} 次`);
				setTimeout(() => fetchPosts(pageNo, categoryId, searchKey), 500);
			} else {
				hasMoreData.value = false;
				retryCount.value = 0; // 达到最大重试次数后重置
			}
		} finally {
			if (!hasMoreData.value || retryCount.value === 0) {
				loading.value = false;
				isLoading.value = false;
			}
			if (isRefreshing.value) {
				isRefreshing.value = false;
			}
		}
	};

	watch(searchValue, (newValue) => {
		if (newValue) {
			currentPage.value = 1; // 搜索时重置页码
			fetchPosts(1, currentCategory.value, newValue);
		} else if (newValue === '') {
			currentPage.value = 1; // 搜索时重置页码
			fetchPosts(1, currentCategory.value, '');
		}
	});

	watch(currentCategory, (newValue) => {
		if (newValue) {
			currentPage.value = 1; // 分类切换时重置页码
			fetchPosts(1, newValue, searchValue.value);
			scrollToTop();
		}
	});

	onMounted(() => {
		if (categories.value.length === 0) {
			fetchCategories();
		}

		// 设置滚动区域高度
		uni.getSystemInfo({
			success: (res) => {
				scrollViewHeight.value = `${res.windowHeight}px`;
			}
		});
	});

	onUnmounted(() => {
		if (scrollTimeout) clearTimeout(scrollTimeout);
	});

	// 增强模式下的滚动事件处理
	const onScroll = (e) => {
		// 增强模式下从e.detail获取scrollTop
		const {
			scrollTop: currentScrollTop
		} = e.detail || {
			scrollTop: 0
		};

		scrollDirection = currentScrollTop > lastScrollTop ? 'down' : 'up';
		lastScrollTop = currentScrollTop;

		// 获取分类栏位置
		uni.createSelectorQuery().select('.category-nav-container').boundingClientRect(rect => {
			if (rect) {
				const categoryTop = rect.top;

				if (scrollDirection === 'down' && categoryTop <= 0) {
					fixedCategoryVisible.value = true;
				} else if (scrollDirection === 'up' && categoryTop >= 0) {
					fixedCategoryVisible.value = false;
				}

				if (currentScrollTop <= 0) {
					fixedCategoryVisible.value = false;
				}
			}
		}).exec();

		// 增强模式下计算滚动加载时机
		uni.createSelectorQuery().select('.z-paging-container').boundingClientRect(rect => {
			if (rect) {
				const containerHeight = rect.height;

				uni.createSelectorQuery().select('.z-paging-container').fields({
					size: true,
					scrollOffset: true,
					computedStyle: ['height']
				}, (res) => {
					if (res) {
						const contentHeight = res.scrollHeight || 0;
						// 距离底部50px时触发加载更多
						if (currentScrollTop + containerHeight >= contentHeight - 50) {
							loadMore();
						}
					}
				}).exec();
			}
		}).exec();
	};

	const handleRefresh = () => {
		isRefreshing.value = true;
		retryCount.value = 0;
		fetchPosts(1, currentCategory.value, searchValue.value);
		scrollToTop();
	};

	const loadMore = () => {
		if (!hasMoreData.value || isLoading.value) {
			return;
		}

		retryCount.value = 0;
		fetchPosts(currentPage.value + 1, currentCategory.value, searchValue.value);
	};

	// 增强模式下的滚动到顶部方法
	const scrollToTop = () => {
		scrollTop.value = Math.random(); // 触发视图更新
		uni.createSelectorQuery().select('.z-paging-container').node((res) => {
			if (res && res.node) {
				res.node.scrollTo({
					scrollTop: 0,
					duration: 300
				});
			}
		}).exec();
	};

	const changeCategory = (id) => {
		if (currentCategory.value === id) return;
		// console.log('点击分类:', id);
		currentCategory.value = id;
		retryCount.value = 0;
		fetchPosts(1, currentCategory.value, searchValue.value);
		scrollToTop();
	};

	// 增强模式下的分类导航滚动
	const scrollCategoryToShowNext = (id) => {
		if (!categoryScroll.value || categoryItemRefs.value.length === 0) return;

		nextTick(() => {
			let targetButton = null;
			if (id === 'latest') {
				targetButton = categoryItemRefs.value[0];
			} else {
				const categoryIndex = categories.value.findIndex(item => item.id === id);
				if (categoryIndex !== -1) {
					targetButton = categoryItemRefs.value[categoryIndex + 1];
				}
			}

			if (!targetButton) return;

			uni.createSelectorQuery().select('.category-scroll').boundingClientRect(containerRect => {
				if (!containerRect) return;

				uni.createSelectorQuery().select(
					`.category-item[data-index="${id === 'latest' ? -1 : categories.value.findIndex(item => item.id === id)}"]`
				).boundingClientRect(buttonRect => {
					if (!buttonRect) return;

					const containerWidth = containerRect.width;
					const buttonRight = buttonRect.right - containerRect.left;

					uni.createSelectorQuery().select('.category-scroll').fields({
						scrollOffset: true
					}, (res) => {
						if (res) {
							const containerScrollLeft = res.scrollLeft;
							let targetScrollLeft = containerScrollLeft;

							if (buttonRight > containerWidth) {
								targetScrollLeft = buttonRect.right - containerWidth +
									20;
							}

							uni.createSelectorQuery().select('.category-scroll')
								.fields({
									scrollOffset: true,
									scrollWidth: true
								}, (scrollInfo) => {
									if (scrollInfo) {
										const contentWidth = scrollInfo
											.scrollWidth;
										const maxScrollLeft = contentWidth -
											containerWidth;
										targetScrollLeft = Math.max(0, Math.min(
											targetScrollLeft, maxScrollLeft
										));

										uni.createSelectorQuery().select(
											'.category-scroll').node(node => {
											if (node && node.node) {
												node.node.scrollTo({
													left: targetScrollLeft,
													behavior: 'smooth'
												});
											}
										}).exec();
									}
								}).exec();
						}
					}).exec();
				}).exec();
			}).exec();
		});
	};

	const onSearch = () => {
		retryCount.value = 0;
		fetchPosts(1, currentCategory.value, searchValue.value);
		scrollToTop();
	};

	const onGiveLike = async (id) => {
		console.log("点赞")

		token.value = uni.getStorageSync("login_data")
		console.log(token.value, 234)
		if (!token.value) {
			// 显示提示文字
			wx.showToast({
				title: '请先登录',
				icon: 'none',
				duration: 1000 // 提示停留2秒
			});

			//延迟2秒后跳转到登录页
			setTimeout(() => {
				wx.switchTab({
					url: '/pages/mine/mine'
				});
			}, 1000);
		}

		let res = await getSchoolIdBy();
		schoolId.value = res.data;
		uni.setStorageSync('school_id', schoolId.value)
		console.log(res, 333333333)
		if (!schoolId.value) {

			wx.showToast({
				title: '请先选择学校',
				icon: 'none',
				duration: 1000 // 提示停留2秒
			});

			// 延迟2秒后跳转到登录页
			setTimeout(() => {
				uni.navigateTo({
					url: `/package/pages/selectSchool/selectSchool`
				});
			}, 1000);

			return;
		}

		let post = list.value.find(item => item.id === id);
		if (!post) {
			post = zhiDingList.value.find(item => item.id === id)
		}
		console.log(post.likestatus, 5555555)
		post.likestatus = post.likestatus === 1 ? 0 : 1;
		post.likeCount = post.likestatus === 1 ?
			(parseInt(post.likeCount) + 1).toString() :
			(parseInt(post.likeCount) - 1).toString();
		// 显示加载状态
		uni.showLoading({
			title: '操作中...'
		});

		try {
			// 发送服务器请求
			const response = await likePost(id, post.likestatus);

			// 处理服务器响应
			if (response.code !== 200) {
				throw new Error(response.message || '操作失败');
			}

			uni.showToast({
				title: post.likestatus === 1 ? '点赞成功' : '取消点赞',
				icon: 'success'
			});
		} catch (error) {
			console.error('点赞请求失败', error);

			// 服务器请求失败时，回滚本地状态
			post.likestatus = post.likestatus === 1 ? 0 : 1;
			post.likeCount = post.likestatus === 1 ?
				(parseInt(post.likeCount) + 1).toString() :
				(parseInt(post.likeCount) - 1).toString();

			uni.showToast({
				title: error.message || '操作失败，请稍后重试',
				icon: 'none'
			});
		} finally {
			uni.hideLoading();
		}
	};


	const tiaoZhuanShouYe = (type) => {
		// scrollToTop();
		wx.switchTab({
			url: '/pages/index/index'
		})
	};
	const navigateTo = (type) => {
		// scrollToTop();
		uni.navigateTo({
			url: `/package/pages/${type}/${type}`
		})
	};

	const showMoreHot = () => {
		scrollToTop();
	};

	const toDetail = (item) => {
		// console.log(item, "-----------")
		// 把点击的帖子基本信息村起来。
		uni.setStorageSync("itemDetail", item)
		// console.log(uni.getStorageSync("itemDetail"))
		uni.navigateTo({
			url: `/package/pages/postDetail/postDetail?id=${item.id}`
		});
	};

	const toPost = () => {
		// 发布之前，看一下是否实名，实名之后才可以发布。
		if (uni.getStorageSync('isrealnameauthenticated')) {
			uni.navigateTo({
				url: `/package/pages/editPost/editPost`
			});
		} else {
			//  未实名，进入实名认证页面
			uni.showToast({
				title: "请先实名",
				icon: 'none',
				duration: 1500
			})
			setTimeout(() => {
				uni.navigateTo({
					url: `/package/pages/smrz/smrz`
				});
			}, 1500);
		}

	};

	const gotoTop = () => {
		scrollToTop();
	};
</script>

<style scoped>
	.category-nav-container-ding {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 100;
		background-color: #f7f7f7;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
	}

	.container {
		background-color: #fff;
		font-family: 'PingFang SC', sans-serif;
	}

	.search-bar {
		padding: 15rpx 20rpx;
	}

	.search-input-container {
		position: relative;
		width: 100%;
	}

	input {
		width: 100%;
		height: 70rpx;
		padding: 0 30rpx;
		background-color: #f7f7f7;
		border-radius: 35rpx;
		font-size: 14px;
		color: #333;
		box-sizing: border-box;
		border: none;
		outline: none;
	}

	input::placeholder {
		color: #999;
		font-size: 26rpx;
	}

	.quick-actions {
		display: flex;
		flex-wrap: nowrap;
	}

	.action-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.hot-rank {
		display: flex;
		align-items: center;
	}

	.rank-swiper {
		height: 100%;
	}

	.category-nav {
		transition: all 0.3s ease;
		z-index: 99;
	}

	.category-nav.fixed {
		top: 0 !important;
		left: 0 !important;
		right: 0 !important;
		z-index: 100 !important;
		background-color: #f7f7f7;
		/* box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15) !important; */
	}

	.category-item {
		display: inline-block;
		padding: 10rpx 25rpx;
		margin: 0 15rpx;
		border-radius: 40rpx;
		font-size: 12px;
		color: #666;
		transition: all 0.3s ease;
	}

	.category-item.active {
		color: #000;
		font-weight: bold;
		font-size: 14px;
	}

	.z-paging-container {
		overflow-y: auto;
	}

	.post-card {
		background-color: #ffffff;
		margin-bottom: 24rpx;
		border-radius: 16rpx;
		overflow: hidden;
	}

	.post-header {
		padding: 24rpx;
	}

	.post-content {
		padding: 24rpx;
	}

	.post-footer {
		padding: 0 24rpx 24rpx 24rpx;
	}

	.post-tags {
		flex-wrap: wrap;
	}

	.tag-item {
		display: flex;
		align-items: center;
		background-color: #f7f7f7;
		padding: 5px 10px;
		border-radius: 25px;
	}

	.like-btn:hover,
	.comment-btn:hover {
		transform: scale(1.05);
	}

	.like-btn:active,
	.comment-btn:active {
		transform: scale(0.95);
	}

	.time {
		color: #999;
		font-size: 24rpx;
	}

	.loading-container {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 20rpx 0;
		position: relative;
		z-index: 10;
	}

	.no-data {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 20rpx 0;
	}

	.no-more-data {
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 20rpx 0;
	}

	.post-button {
		position: fixed;
		right: 15px;
		bottom: 100px;
		z-index: 99;
	}


	.rank-number {
		width: 48rpx;
		height: 48rpx;
		line-height: 48rpx;
		border-radius: 12rpx;
		text-align: center;
		font-size: 26rpx;
		margin-right: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		/* asdf */
	}
</style>